package cn.jinjimi.framework.router.impl;

import android.os.Bundle;

import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.framework.helper.annotation.QueryKey;
import cn.jinjimi.framework.router.RouterOptions;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;

/**
 * Created by jinsen on 15/9/17.
 */
public class EventRTask implements IRTask {

    Object mEvent;

    public EventRTask(Object event) {
        mEvent = event;
    }

    @Override
    public void open(RouterOptions option) {
        Bundle bundle = option.getBundle();
        Field[] fields = mEvent.getClass().getDeclaredFields();
        for (Field f : fields) {
            QueryKey key = f.getAnnotation(QueryKey.class);
            try {
                f.setAccessible(true);

                String value = null;
                if (bundle.get(key.value()) instanceof String)
                    value = bundle.getString(key.value());

                if (StringUtils.isNotEmpty(value)) {
                    value = URLDecoder.decode(value, "utf-8");
                }

                f.set(mEvent, value);
            } catch (IllegalAccessException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        EventBus.getDefault().post(mEvent);
    }

}